package com.gw.booking.service;

import com.gw.booking.entity.LoginToken;
import config.Config;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.UUID;

@Service
public class LoginTokenService {
	@Autowired
	SessionFactory sessionFactory;

	/**
	 * 删除token
	 * @param loginToken
	 */
	public void txDelete(LoginToken loginToken) {
		Session session = sessionFactory.getCurrentSession();
		
		session.delete(loginToken);
		

	}
	
	/**
	 * 刷新token信息
	 */
	public LoginToken txRefreshLoginToken(String token) {
		Session session = sessionFactory.getCurrentSession();

		LoginToken loginToken = (LoginToken)session.createCriteria(LoginToken.class)
				.add(Restrictions.eq("token", token))
				.add(Restrictions.ge("timeLimit", System.currentTimeMillis()))
				.uniqueResult();

		if (loginToken != null) {
			loginToken.setTimeLimit(System.currentTimeMillis() + Config.loginTokenLimit);
			loginToken.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
			session.update(loginToken);
			session.flush();
		}

		return loginToken;
	}
	
	/**
	 * 添加token
	 * @param session
	 * @param type 用户类型
	 * @param userId 用户id
	 * @param ip 客户端ip
	 */
	public LoginToken txAddLoginToken(Session session, String type, int userId, String ip, Integer cityId) {
		LoginToken loginToken = new LoginToken();
		loginToken.setType(type);
		loginToken.setUserId(userId);
		loginToken.setIp(ip);
		loginToken.setTimeLimit(System.currentTimeMillis() + Config.loginTokenLimit);
		loginToken.setToken(UUID.randomUUID().toString());
		loginToken.setCreatedAt(new Timestamp(System.currentTimeMillis()));
		loginToken.setCityId(cityId);
		session.save(loginToken);
		session.flush();
		return loginToken;
	}
    
    /**
     * 清理过期token
     */
    public void clearOverdueTokens() {
        Session session = sessionFactory.getCurrentSession();
        String hql = ""
                + "    delete from LoginToken "
                + "    where timeLimit < :currentTime";
        
        session.createQuery(hql).setLong("currentTime", System.currentTimeMillis()).executeUpdate();
        session.flush();
    }
}
